const Service = require("egg").Service;

class BannerService extends Service {
  async findList(query) {
    let { pageSize, currentPage } = query;
    pageSize = pageSize || 10;
    currentPage = currentPage || 1;
    if (query.name) {
      return await this.ctx.model.Banner.find({ name: { $regex: query.name } })
        .limit(+pageSize)
        .skip((+currentPage - 1) * pageSize)
        .sort({ sort: -1 });
    } else {
      return await this.ctx.model.Banner.find({})
        .limit(+pageSize)
        .skip((+currentPage - 1) * pageSize)
        .sort({ sort: -1 });
    }
  }

  async fetchTotal(){
    return await this.ctx.model.Banner.find({});
  }


  // 新增
  async add(Banner) {
    return await this.ctx.model.Banner.create(Banner);
  }

  // 修改
  async update(Banner) {
    return await this.ctx.model.Banner.findOneAndUpdate(
      {
        _id: Banner._id
      },
      Banner
    );
  }

  // 批量删除
  async delete(_ids) {
    return await this.ctx.model.Banner.deleteMany({
      _id: { $in: _ids }
    });
  }

  /**
   * {
   *   name:'',
   *   icon:'',
   *   foods:[]
   *
   * }
   * @returns {Promise<void>}
   */
  async fetchAll() {
    const menus = await this.ctx.model.Banner.find({});
    const commodities = await this.ctx.model.Commodity.find({});
    if (menus) {
      for (let menu of menus) {
        if (commodities) {
          let foods = [];
          for (let food of commodities) {
            if (menu._id.toString() === food.menuId.toString()) {
              foods.push(food);
            }
          }
          menu.foods = foods;
          // console.log(menu)
        } else {
          menu.food = [];
        }
      }
    }
    return menus.sort((a, b) => b.sort - a.sort);
  }
}

module.exports = BannerService;
